package cn.eshore.bnet.sag.fax;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.Header;



/**
 * 客户端工具.
 * 
 * @author zhoujinhuang
 * 
 */
public final class ClientUtils {
	public static final String DF_HEADER_TIMESTAMP = "yyyyMMddHHmmssSSS";
	public static final String DATEFORMAT_SIMPLE = "yyyyMMddHHmmss";

	private ClientUtils() {
	}

	/**
	 * 将消息头的时间戳，转为Data类型
	 * 
	 * @param timestamp
	 *            时间对象
	 * @return 格式化后的时间字符串
	 * @throws ParseException
	 */
	public static Date getSigningTimestamp(String timestamp)
			throws ParseException {
		final DateFormat df = new SimpleDateFormat(DF_HEADER_TIMESTAMP);
		return df.parse(timestamp);
	}

	/**
	 * 根据Data类型时间产生消息头的时间戳。
	 * 
	 * @param timestamp
	 *            时间对象
	 * @return 格式化后的时间字符串
	 * @throws ParseException
	 */
	public static String getSigningTimestamp(Date date) throws ParseException {
		final DateFormat df = new SimpleDateFormat(DF_HEADER_TIMESTAMP);
		return df.format(date);
	}

	/**
	 * 按指定的格式解析字符串时间对象.
	 * 
	 * @parham timestamp 时间对象
	 * @return 格式化后的时间字符串
	 * @throws ParseException
	 */
	public static Date parseDate(String timestamp, String format)
			throws ParseException {
		final DateFormat df = new SimpleDateFormat(format);
		return df.parse(timestamp);
	}

	/**
	 * 
	 * 计算签名
	 * 
	 * @param content
	 * @param algorithm
	 * @return
	 */
	private static String getDigest(String content, String algorithm) {
		try {
			byte[] plainText = content.getBytes();
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(plainText);
			byte[] digest = messageDigest.digest();
			return byte2hex(digest);
		} catch (NoSuchAlgorithmException ex) {
			System.out.println("Error digest algorithm: " + algorithm);
		}
		return null;
	}

	/**
	 * 根据si 密码 时间戳 计算签名。
	 * 
	 * @param si
	 * @param password
	 * @param timestamp
	 * @return
	 */
	public static String getSignature(String si, String password,
			String timestamp) {
		return getDigest(si + password + timestamp, "md5");
	}

	/**
	 * 
	 * 转换为字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs.append("0" + stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString();
	}

	/**
	 * 按指定的格式解析字符串时间对象.
	 * 
	 * @param timestamp
	 *            时间对象
	 * @return 格式化后的时间字符串
	 * @throws ParseException
	 */
	public static String formatDate(Date date, String format)
			throws ParseException {
		final DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	/**
	 * 
	 * 各参数意义，请参见《广东商企平台能力开放接口协议-总册.doc》
	 * 
	 * @param si
	 * @param password
	 *            //平台分配给si的密码，用于计算签名
	 * @param bnetId
	 * @param user
	 * @param product
	 * @param productSpec
	 * @param accessNumber
	 * @param accounting
	 * @return
	 * @throws ParseException
	 */
	public static Header createHeader(String si, String password,
			String bnetId, String user, String product, String productSpec,
			String accessNumber, String accounting) throws ParseException {
		String timestamp = getSigningTimestamp(new Date());
		// 计算签名
		String signature = getSignature(si, password, timestamp);
		Header header = new Header();
		header.setSi(si);
		header.setSignature(signature);
		header.setTimestamp(timestamp);
		header.setProduct(product);
		header.setAccessNumber(accessNumber);
		header.setAccounting(accounting);
		header.setProductSpec(productSpec);
		header.setPurchaser(bnetId);
		header.setUser(user);
		return header;
	}

//	public static String getExceptionMessage(Exception e) {
//		if (e instanceof ServiceException_Exception) {
//			return "连接服务系统异常,返回 错误编码："
//					+ ((ServiceException_Exception) e).getFaultInfo()
//							.getErrorCode() + " 提示消息："
//					+ ((ServiceException_Exception) e).getMessage();
//		}
//		if (e instanceof PolicyException_Exception) {
//			return "连接服务系统异常,返回 错误编码："
//					+ ((PolicyException_Exception) e).getFaultInfo()
//							.getErrorCode() + " 提示消息："
//					+ ((PolicyException_Exception) e).getMessage();
//		}
//		return "连接服务系统异常," + e.getMessage();
//	}

	
	public static String saveAttachment(Attachment attachment, String path)
			throws IOException {
		String name = attachment.getName();

		String file = path + "/" + name;
		InputStream in = null;
		OutputStream out = null;
		try {
			int ch;
			in = attachment.getData().getInputStream();
			out = new BufferedOutputStream(new FileOutputStream(file));
			while ((ch = in.read()) != -1) {
				out.write(ch);
			}

			return file;
		} catch (IOException e) {
			throw e;
		} finally {
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		}
	}
}
